package rcs34.android.AndroidRC;

public class RC4 {
  private int[] s;
  private int[] initialS;
  private String password;
  
  public RC4(String _key) {
    password=_key;
    byte[] key=password.getBytes();
    s = new int[256];
    for (int i = 0; i < 256; i++) {
      s[i] = i;
    }
    int j = 0;
    for (int i = 0; i < 256; i++) {
      j = (j + s[i] + key[i % _key.length()]) % 256;
      this.swapS(i, j);
    }
    initialS=new int[256];
    System.arraycopy(s, 0, initialS, 0, 256);
  }
  
  public void reset(){
    System.arraycopy(initialS, 0, s, 0, 256);
  }
  
  public byte[] proceed(byte[] _data) {
    byte[] result = new byte[_data.length];
    int i = 0;
    int j = 0;
    for (int d = 0; d < _data.length; d++) {
      i = (i + 1) % 256;
      j = (j + s[i]) % 256;
      swapS(i, j);
      result[d] = (byte) (s[(s[i] + s[j]) % 256] ^ _data[d]);
    }
    return result;
  }
  
  private void swapS(int _i, int _j) {
    int temp = s[_i];
    s[_i] = s[_j];
    s[_j] = temp;
  }
  
  public String getPassword(){
    return password;
  }
}
